package com.ruicar.afs.cloud.finance.common.service.impl;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ruicar.afs.cloud.common.core.exception.AfsBaseException;
import com.ruicar.afs.cloud.common.modules.contract.enums.FundsTypeEnum;
import com.ruicar.afs.cloud.common.modules.contract.enums.UnusedFundsStatusEnums;
import com.ruicar.afs.cloud.common.mq.finance.debit.dto.StartReceiptHandleDto;
import com.ruicar.afs.cloud.common.mq.rabbit.message.AfsTransEntity;
import com.ruicar.afs.cloud.common.mq.rabbit.message.MqTransCode;
import com.ruicar.afs.cloud.finance.common.entity.FinanceCustUnusedFunds;
import com.ruicar.afs.cloud.finance.common.entity.FinanceVirtualAccount;
import com.ruicar.afs.cloud.finance.common.mapper.FinanceVirtualAccountMapper;
import com.ruicar.afs.cloud.finance.common.service.FinanceCustUnusedFundsService;
import com.ruicar.afs.cloud.finance.common.service.FinanceVirtualAccountService;
import com.ruicar.afs.cloud.finance.mq.sender.ReceiptSender;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;

/**
 * <p>Description: </p>
 *
 * @author ZC.GUO
 * @version 1.0
 * @date create on 2020-07-02 10:18
 */
@Service
@Slf4j
@AllArgsConstructor
@EnableAsync
public class FinanceVirtualAccountServiceImpl extends ServiceImpl<FinanceVirtualAccountMapper, FinanceVirtualAccount> implements FinanceVirtualAccountService {

    private final FinanceVirtualAccountMapper financeVirtualAccountMapper;
    private final FinanceCustUnusedFundsService financeCustUnusedFundsService;
    private final ReceiptSender receiptSender;

    @Override
    public void updateWhenDistribution(FinanceVirtualAccount virtualAccount, BigDecimal amount) {

        int num = financeVirtualAccountMapper.updateWhenDistribution(amount,virtualAccount.getId(),virtualAccount.getRevision());

        if (num < 1){
            log.warn("乐观锁生效，数据更新失败，虚拟账户id为：{}，乐观锁值为{}",virtualAccount.getId(),virtualAccount.getRevision());
            throw new AfsBaseException("乐观锁生效，数据更新失败，虚拟账户id为："+virtualAccount.getId());
        }
    }

    @Override
    @Async
    @Transactional(rollbackFor = Exception.class)
    public void handleUnusedFundsForOne(FinanceVirtualAccount virtualAccount){
        List<FinanceCustUnusedFunds> custUnusedFundsList = financeCustUnusedFundsService.list(Wrappers.<FinanceCustUnusedFunds>query().lambda()
                .eq(FinanceCustUnusedFunds::getAccountId,virtualAccount.getId())
                /**  只能对分配后结余的金额进行处理，撤销后暂存的金额不进行处理 by ZC.GUO  **/
                .eq(FinanceCustUnusedFunds::getFundsType, FundsTypeEnum.surplus)
                /**  只能处理可处理的金额，锁定状态的金额不能处理 by ZC.GUO  **/
                .eq(FinanceCustUnusedFunds::getStatus, UnusedFundsStatusEnums.mayuse)
                /**  金额大于0 by ZC.GUO  **/
                .gt(FinanceCustUnusedFunds::getAmount,BigDecimal.ZERO));

        if (custUnusedFundsList != null && custUnusedFundsList.size()>0){

            List<Long> receiptIdList = new ArrayList<>();
            for (FinanceCustUnusedFunds financeCustUnusedFunds : custUnusedFundsList){
                /**  状态更新成功则进行发送 by ZC.GUO  **/
                financeCustUnusedFunds.setStatus(UnusedFundsStatusEnums.locked);
                if (financeCustUnusedFundsService.updateWhenStartDistribution(financeCustUnusedFunds)){
                    receiptIdList.add(financeCustUnusedFunds.getFundId());
                }
            }

            /**  组装消息 by ZC.GUO  **/
            AfsTransEntity<StartReceiptHandleDto> entity = new AfsTransEntity<>();
            StartReceiptHandleDto startReceiptHandleDto = new StartReceiptHandleDto();
            startReceiptHandleDto.setAccountId(virtualAccount.getId());
            startReceiptHandleDto.setIdList(receiptIdList);
            startReceiptHandleDto.setOperator("system");
            entity.setData(startReceiptHandleDto);
            entity.setTransCode(MqTransCode.AFS_CONTRACT_FINANCE_BASIC_CONTRACT_START_RECEIPTHANDLE);
            receiptSender.sendReceiptDealOrder(entity);

        }
    }
}
